<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.userId"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入用户ID"
      />
      <el-input
        v-model="listQuery.orderSn"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入订单编号"
      />
      <el-select
        v-model="listQuery.orderStatus"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择订单状态"
      >
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-button
        v-permission="['GET /admin/order/list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" min-width="100" label="订单编号" prop="orderSn" />

      <el-table-column align="center" label="用户ID" prop="userId" />

      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.orderStatus | orderStatusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="orderPrice" />

      <el-table-column align="center" label="支付金额" prop="actualPrice" />

      <!-- <el-table-column align="center" label="支付时间" prop="payTime" /> -->

      <el-table-column align="center" label="物流单号" prop="shipSn" />

      <!-- <el-table-column align="center" label="物流渠道" prop="shipChannel" /> -->

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['GET /admin/order/detail']"
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            v-if="scope.row.orderStatus==2"
            v-permission="['POST /admin/order/ship']"
            type="primary"
            size="mini"
            @click="handleShip(scope.row)"
          >发货</el-button>
          <el-button
            v-if="scope.row.orderStatus==-5"
            v-permission="['POST /admin/order/refund']"
            type="primary"
            size="mini"
            @click="handleRefund(scope.row)"
          >退款</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情" width="800">
      <section ref="print">
        <el-form :data="orderDetail" label-position="left">
          <el-form-item label="订单编号">
            <span>{{ orderDetail.ordersVO.orderSn }}</span>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-tag>{{ orderDetail.ordersVO.orderStatus | orderStatusFilter }}</el-tag>
          </el-form-item>
          <el-form-item label="订单用户">
            <span>{{ orderDetail.user.nickname }}</span>
          </el-form-item>
          <el-form-item label="用户留言">
            <span>{{ orderDetail.ordersVO.userMessage }}</span>
          </el-form-item>
          <el-form-item label="收货信息">
            <span>（收货人）{{ orderDetail.ordersVO.consignee }}</span>
            <span>（手机号）{{ orderDetail.ordersVO.mobile }}</span>
            <span>（地址）{{ orderDetail.ordersVO.address }}</span>
          </el-form-item>
          <el-form-item label="商品信息">
            <el-table :data="orderDetail.orderGoods" border fit highlight-current-row>
              <el-table-column align="center" label="商品名称" prop="goodsName" />
              <el-table-column align="center" label="商品编号" prop="goodsSn" />
              <!-- <el-table-column align="center" label="货品规格" prop="specifications" /> -->
              <el-table-column align="center" label="货品价格" prop="price" />
              <el-table-column align="center" label="货品数量" prop="number" />
              <el-table-column align="center" label="货品图片" prop="picUrl">
                <template slot-scope="scope">
                  <img :src="scope.row.picUrl" width="40">
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="费用信息">
            <span>(实际费用){{ orderDetail.ordersVO.actualPrice }}元 = (商品总价){{ orderDetail.ordersVO.goodsPrice }}元 + (快递费用){{ orderDetail.ordersVO.freightPrice }}元 - (优惠减免){{ orderDetail.ordersVO.couponPrice }}元 - (积分减免){{ orderDetail.ordersVO.integralPrice }}元</span>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printOrder">打 印</el-button>
      </span>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog :visible.sync="shipDialogVisible" title="发货">
      <el-form
        ref="shipForm"
        :model="shipForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="快递公司">
          <el-input disabled="true" value="同城速递" />
        </el-form-item>
        <el-form-item v-show="false" label="订单状态">
          <el-input v-model="shipForm.orderStatus" disabled="true" placeholder="待收货" value="3" />
        </el-form-item>
        <el-form-item label="快递编号" prop="shipSn">
          <el-input v-model="shipForm.shipSn" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确定</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible" title="退款">
      <el-form
        ref="refundForm"
        :model="refundForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="退款理由" prop="refundMoney">
          <el-input v-model="refundForm.reason" disabled />
        </el-form-item>
        <el-form-item label="退款图片">
          <img v-for="url in refundForm.reasonUrl" :src="url" class="avatar">
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refuseRefund">拒绝</el-button>
        <el-button type="primary" @click="confirmRefund">接受</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>
<script>
import {
  detailOrder,
  listOrder,
  listChannel,
  refundOrder,
  shipOrder,
  drawBackInfo,
  orderConfirm,
  orderRefuse
} from '@/api/order';
import Pagination from '@/components/Pagination'; // Secondary package based on el-pagination
import checkPermission from '@/utils/permission'; // 权限判断函数

const statusMap = {
  1: '未付款',
  2: '待发货',
  3: '待收货',
  4: '用户收货',
  5: '完成交易',
  '-1': '用户取消',
  '-3': '系统取消',
  '-5': '申请退款',
  '-6': '已退款'
};

export default {
  name: 'Order',
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status];
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        name: undefined,
        content: undefined,
        orderBy: 'add_time',
        sort: 'desc'
      },
      statusMap,
      orderDialogVisible: false,
      orderDetail: {
        ordersVO: {},
        user: {},
        orderGoods: []
      },
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined,
        orderStatus: 3
      },
      shipDialogVisible: false,
      refundForm: {
        id: undefined,
        reason: undefined,
        reasonUrl: undefined,
        orderId: undefined,
        refundMoney: undefined,
        userId: undefined,
        actualPrice: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      channels: []
    };
  },
  created() {
    this.getList();
    // this.getChannel();
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      listOrder(this.listQuery)
        .then(response => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    getChannel() {
      listChannel().then(response => {
        this.channels = response.data.data;
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.getList();
    },
    created() {
      this.getList();
      // this.getChannel()
    },
    handleDetail(row) {
      detailOrder(row.id).then(response => {
        this.orderDetail = response.data.data;
        this.orderDetail.user = this.orderDetail.user || { nickname: '' };
      });
      this.orderDialogVisible = true;
    },
    handleShip(row) {
      this.shipForm.id = row.id;
      this.shipForm.shipChannel = row.shipChannel;
      this.shipForm.shipSn = row.shipSn;

      this.shipDialogVisible = true;
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate();
      });
    },
    confirmShip() {
      this.$refs['shipForm'].validate(valid => {
        if (valid) {
          shipOrder(this.shipForm)
            .then(response => {
              this.shipDialogVisible = false;
              this.$notify.success({
                title: '成功',
                message: '确认发货成功'
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              });
            });
        }
      });
    },
    handleRefund(row) {
      drawBackInfo({ id: row.id }).then(response => {
        this.refundDialogVisible = true;
        this.refundForm = response.data.data;
        this.refundForm.reasonUrl = this.refundForm.reasonUrl.split(',');
      });
    },
    refuseRefund() {
      orderRefuse({ id: this.refundForm.orderId }).then(res => {
        this.refundDialogVisible = false;
        this.getList();
      });
    },
    confirmRefund() {
      orderConfirm({ id: this.refundForm.orderId }).then(response => {
        this.refundDialogVisible = false;
        this.getList();
      });
      return;x
      this.$refs['refundForm'].validate(valid => {
        if (valid) {
          refundOrder(this.refundForm)
            .then(response => {
              this.refundDialogVisible = false;
              this.$notify.success({
                title: '成功',
                message: '确认退款成功'
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              });
            });
        }
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '订单ID',
          '订单编号',
          '用户ID',
          '订单状态',
          '是否删除',
          '收货人',
          '收货联系电话',
          '收货地址'
        ];
        const filterVal = [
          'id',
          'orderSn',
          'userId',
          'orderStatus',
          'isDelete',
          'consignee',
          'mobile',
          'address'
        ];
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息');
        this.downloadLoading = false;
      });
    },
    printOrder() {
      this.$print(this.$refs.print);
      this.orderDialogVisible = false;
    }
  }
};
</script>
